﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Threading;
using Best.Framework.Web;
using XMK.BatchImport.Model;
using XMK.Framework.Model.Cond;
using XMK.Utils;
using XMK.Framework.Model;
using System.Configuration;

namespace XMK.BatchImport
{
    public partial class Mainfrm : Form
    {

        private int targetValue = 0;
        // private Queue<string> qlist = new Queue<string>();//附件地址队列
        //private bool IsEnd = false;//是否数据到最后
        private string _folderpath = "";
        private string theFolder = "";
        private string nodeID; 
        string DiskPath = ConfigurationManager.AppSettings["DiskPath"];//@"D:/TaDongDoc/";
        //文件夹按照日期创建
        string FolderNmae = System.DateTime.Now.ToString("yyyyMMdd");
        string user_id;
        private string NewFileName;//重命名后的全局唯一名
        public Mainfrm(string User_id)
        {
            InitializeComponent();
            //tbFile.Text = User_id;
            this.user_id = User_id;
        }

        /// <summary>
        /// 选择文件夹
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tbFile_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                tbFile.Text = openFileDialog1.FileName;
            }
        }

        /// <summary>
        /// 上传
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            //IsEnd = false;
            if (tbFile.Text == "" || tbTagert.Text == "")
            {
                MessageBox.Show("上传参数文件和目标不能为空！");
                return;
            }
            nodeID = targetValue.ToString();
            _folderpath = FolderNmae + "/";//DateTime.Now.ToString("yyyy") + "/" + DateTime.Now.ToString("MM") + "/" + DateTime.Now.ToString("dd") + "/" + DateTime.Now.ToString("hhmmss") + "/";
            labelfail.Text = "0";
            labelcount.Text = "0";
            labeldb.Text = "0";
            labeldbfail.Text = "0";
            progressBar1.Value = 0;
            progressBar2.Value = 0;


            FileInfo file = new FileInfo(tbFile.Text);
            theFolder = file.DirectoryName;
            DataSet ds = Best.Framework.Web.ExcelHelper.ReadExcelToDataset(file.FullName, 1);
            if (ds != null && ds.Tables.Count > 0)
            {
                string _sum = "/" + ds.Tables[0].Rows.Count.ToString();
                labeldbsum.Text = _sum;
                labeldbsum2.Text = _sum;
                labelsum.Text = _sum;
                labelsum2.Text = _sum;
                labelsum3.Text = _sum;
                progressBar1.Maximum = ds.Tables[0].Rows.Count;
                progressBar2.Maximum = ds.Tables[0].Rows.Count;

                Thread td = new Thread(new ParameterizedThreadStart(attachUpload));
                td.IsBackground = true;
                td.Start(ds.Tables[0]);
            }


        }

        /// <summary>
        /// 插入数据库
        /// </summary>
        /// <param name="obj"></param>
        private void InsertDb(DataRow dr, string _filesize)
        {
            try
            {
                ////重命名文件
                //NewFileName = DateTime.Now.ToFileTimeUtc() + dr[0].ToString().Substring(dr[0].ToString().LastIndexOf('.'));
                string save_path = "Project" + "/" + FolderNmae + "/" + NewFileName; //dr[0].ToString();//+ NewFileName;
                string filext = dr[0].ToString().Substring(dr[0].ToString().LastIndexOf('.') + 1);
                FileAddCond filecond = new FileAddCond()
                {
                    FILE_NAME = dr[0].ToString(),//文件名
                    FILE_EXT = filext,//文档格式
                    FILE_ABST = dr[1].ToString(),//摘要
                    FILE_AUTHOR = dr[2].ToString(),//作者
                    KEYW = dr[3].ToString(),//关键词
                    DEST_OBJ = dr[4].ToString(),//目标
                    BIZ_OBJ = dr[5].ToString(),//业务
                    LANG_TYPE = 0,
                    SAVE_PATH = save_path,// "project/待审核/" + _folderpath + dr[11].ToString().Replace("/" + NewFileName.ToString(), ""),//保存路径
                    FILE_SIZE = _filesize,//文件大小
                    USER_ID = user_id,//dr[9].ToString(),
                    FOLDER_ID = int.Parse(nodeID),
                    FILE_CRT_DATE = DateTime.Parse(dr[6].ToString()),//形成时间
                    FORM_UNIT = dr[7].ToString(),//所属单位
                    TEAM_NAME = dr[8].ToString(),//来源项目
                    TEAM_ID=17,
                    STATUS = 1
                };
                //if (dr[8].ToString() != "")
                //{
                //    filecond.TEAM_ID = 17;//int.Parse(dr[8].ToString());
                //}
                CommonDataCond cond = new CommonDataCond();

                cond.ws = new WsCond();
                cond.ws.wsId = "BatInsertFile";
                cond.ws.logId = "1111111";
                cond.ws.callDatetime = DateHelper.ConvertString(DateTime.Now, DateHelper.FORMAT_yyyy_MM_dd_HH_mm_ss_fff);
                cond.ws.ipAddr = "10.100.100.100";
                cond.ws.supplierId = "xmk";
                cond.cond = filecond;
                string s = JsonHelper.ToJson(cond);
                TadongWS.WSService service = new TadongWS.WSService();
                string retstr = service.callService(s);
                var commdatainfo = JsonHelper.FromJson<CommonDataInfo>(retstr);

                if (commdatainfo.ms.code == "0")
                {
                    this.labeldb.Invoke(new Action(() =>
                    {
                        progressBar1.Increment(1);
                        labeldb.Text = "" + (int.Parse(labeldb.Text) + 1);
                    }));
                }
                else
                {
                    this.labeldb.Invoke(new Action(() =>
                    {
                        progressBar1.Increment(1);
                        labeldbfail.Text = "" + (int.Parse(labeldbfail.Text) + 1);
                        tberr.Text += "数据插入失败" + commdatainfo.ms.msg;
                    }));
                }

            }
            catch (Exception ex)
            {
                this.labeldbfail.Invoke(new Action(() =>
                {
                    labeldbfail.Text = "" + (int.Parse(labeldbfail.Text) + 1);
                    progressBar1.Increment(1);
                    tberr.Text += "数据插入异常" + ex.Message;

                }));
            }
        }

        /// <summary>
        /// 上传附件
        /// </summary>
        /// <param name="obj"></param>
        private void attachUpload(object obj)
        {
            DataTable dt = (DataTable)obj;
            FtpHelper ftp = new FtpHelper();
            ftp.FtpUpDown(Config.ftpIP, Config.ftpUser, Config.ftpPassword);
            try
            {

                foreach (DataRow dr in dt.Rows)
                {
                    QueueHandler(theFolder, ftp, dr);
                }

                this.Invoke(new Action(() => { MessageBox.Show("导入完成"); }));
            }
            catch (Exception ex)
            {
                this.tberr.Invoke(new Action(() =>
                {
                    tberr.Text += "FTP异常" + ex.Message;
                }));
            }
        }

        /// <summary>
        /// 处理队列中的文件
        /// </summary>
        /// <param name="_foldcond"></param>
        /// <param name="ftp"></param>
        /// <param name="dr"></param>
        private void QueueHandler(string _foldcond, FtpHelper ftp, DataRow dr)
        {
            string filename = dr[0].ToString();
            //重命名文件
            NewFileName = DateTime.Now.ToFileTimeUtc() + filename.Substring(filename.LastIndexOf('.'));
            if (!string.IsNullOrEmpty(filename))
            {
                string _currentfilepath = _foldcond + "\\" + filename;
                string[] patharr = filename.Replace("\\", "/").Split('/');
                string subfolder = "";
                if (patharr.Length > 1)
                {
                    for (int i = 0; i < patharr.Length - 1; i++)
                    {
                        subfolder += patharr[i] + "/";
                    }
                }
                string _ftpfolder = _folderpath + "/"; //+ subfolder;
                //当前文件是否存在
                if (!File.Exists(_currentfilepath))
                {
                    this.labelcount.Invoke(new Action<string, string>((string _fileinfo, string _err) =>
                    {
                        progressBar1.Increment(1);
                        labeldbfail.Text = "" + (int.Parse(labeldbfail.Text) + 1);
                        progressBar2.Increment(1);
                        labelfail.Text = "" + (int.Parse(labelfail.Text) + 1);
                        tberr.Text += _fileinfo + _err + "\r\n";
                    }), _currentfilepath, "文件不存在");
                }
                else
                {
                    FileInfo file = new FileInfo(_currentfilepath);
                    string _filesize = ViewSize(file.Length);
                    ftpUpload(ftp, _currentfilepath, _ftpfolder, dr, _filesize);
                }
            }
            else//无效
            {
                this.labelinvalid.Invoke(new Action(() =>
                {
                    progressBar1.Increment(1);
                    labeldbfail.Text = "" + (int.Parse(labeldbfail.Text) + 1);
                    progressBar2.Increment(1);
                    labelinvalid.Text = "" + (int.Parse(labelinvalid.Text) + 1);
                }));
            }
        }

        public string ViewSize(long size)
        {
            long m = size;
            string viewstr;

            if ((m / 1024) > 0)//表示可以转换成KB  
            {
                m = m / 1024;//转换成KB  

                if ((m / 1024) > 0)//表示可以转换成MB  
                {
                    m = m / 1024;//转换成MB了  

                    if ((m / 1024) > 0)//表示可以转换成GB  
                    {
                        m = m / 1024;//转换成GB了  
                        viewstr = m.ToString() + "GB";
                    }
                    else
                    {
                        viewstr = m.ToString() + "MB";
                    }
                }
                else
                {
                    viewstr = m.ToString() + "KB";
                }
            }
            else
            {
                viewstr = m.ToString() + "byte";
            }
            return viewstr;
        }

        /// <summary>
        /// FTP上传
        /// </summary>
        /// <param name="ftp"></param>
        /// <param name="_currentfilepath"></param>
        /// <param name="_ftpfolder"></param>
        private void ftpUpload(FtpHelper ftp, string _currentfilepath, string _ftpfolder, DataRow dr, string _filesize)
        {

            ftp.FtpCheckDirectoryExist(_ftpfolder);
            string err = "";
            if (!ftp.Upload(_currentfilepath, _ftpfolder, out err, NewFileName))
            {
                this.labelcount.Invoke(new Action<string, string>((string _fileinfo, string _err) =>
                {
                    progressBar2.Increment(1);
                    labelfail.Text = "" + (int.Parse(labelcount.Text) + 1);
                    tberr.Text += _fileinfo + _err + "\r\n";
                    progressBar1.Increment(1);
                    labeldbfail.Text = "" + (int.Parse(labeldbfail.Text) + 1);
                }), _currentfilepath, err);
            }
            else
            {
                InsertDb(dr, _filesize);
                this.labelcount.Invoke(new Action(() =>
                {
                    progressBar2.Increment(1);
                    labelcount.Text = "" + (int.Parse(labelcount.Text) + 1);
                }));
            }
        }

        /// <summary>
        /// 打开目标树
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tbTagert_Click(object sender, EventArgs e)
        {
            TargetFrm targetfrm = new TargetFrm();
            targetfrm.targetevent += new TargetFrm.delSetTargetValue(setTarget);
            targetfrm.ShowDialog();
        }

        public void setTarget(string text, int value)
        {
            tbTagert.Text = text;
            targetValue = value;
        }

        private void Mainfrm_Load(object sender, EventArgs e)
        {

        }

       
    }
}
